/**
 * 监控仪表板页面组件
 * 
 * 功能特性：
 * - 完整的监控仪表板页面
 * - 多标签页支持
 * - 自定义布局
 * - 实时数据更新
 * 
 * @author CKY Agent Platform Team
 * @version 1.0.0
 * @lastModified 2024-01-15
 */

import React, { useState, useEffect, useCallback } from 'react';
import { 
  Card, 
  Tabs, 
  Row, 
  Col, 
  Statistic, 
  Progress, 
  Button, 
  Space, 
  Select, 
  DatePicker, 
  Alert,
  Modal,
  Form,
  Input,
  Switch,
  InputNumber,
  message,
  Spin,
  Tag,
  Typography,
  Divider
} from 'antd';
import {
  DashboardOutlined,
  LineChartOutlined,
  BarChartOutlined,
  PieChartOutlined,
  SettingOutlined,
  ReloadOutlined,
  FullscreenOutlined,
  DownloadOutlined,
  BellOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  ClockCircleOutlined,
  ArrowsAltOutlined,
  ShrinkOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined
} from '@ant-design/icons';
import RealTimeDashboard from '@components/Monitoring/RealTimeDashboard';
import MonitoringService from '@services/monitoringService';
import { 
  DashboardConfig, 
  SystemMetrics, 
  AlertInfo, 
  PerformanceStats,
  HealthStatus,
  TimeRange,
  AlertRule,
  NotificationChannel
} from '../types/monitoring';
import './MonitoringDashboard.css';

const { Title, Text } = Typography;
const { Option } = Select;
const { RangePicker } = DatePicker;

interface MonitoringDashboardProps {
  // 可以在这里添加props
}

const MonitoringDashboard: React.FC<MonitoringDashboardProps> = () => {
  const [loading, setLoading] = useState(false);
  const [realTimeMetrics, setRealTimeMetrics] = useState<SystemMetrics[]>([]);
  const [alerts, setAlerts] = useState<AlertInfo[]>([]);
  const [performanceStats, setPerformanceStats] = useState<PerformanceStats | null>(null);
  const [healthStatus, setHealthStatus] = useState<HealthStatus | null>(null);
  const [dashboardConfig, setDashboardConfig] = useState<DashboardConfig>({
    refreshInterval: 5000,
    enabledWidgets: ['system', 'performance', 'alerts'],
    alertThresholds: {
      cpu: 80,
      memory: 85,
      disk: 90,
      responseTime: 5000
    },
    theme: 'light'
  });
  const [selectedTimeRange, setSelectedTimeRange] = useState<TimeRange>('1h');
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [settingsModalVisible, setSettingsModalVisible] = useState(false);
  const [alertRulesModalVisible, setAlertRulesModalVisible] = useState(false);
  const [activeTab, setActiveTab] = useState('realtime');
  
  const monitoringService = new MonitoringService(
    process.env.REACT_APP_API_URL || 'http://localhost:6001',
    localStorage.getItem('token') || ''
  );

  // 获取实时数据
  const fetchRealTimeData = useCallback(async () => {
    setLoading(true);
    try {
      const [metrics, alertsData, healthData] = await Promise.all([
        monitoringService.getSystemMetrics(selectedTimeRange),
        monitoringService.getAlerts('active'),
        monitoringService.getHealthStatus()
      ]);
      
      setRealTimeMetrics(metrics);
      setAlerts(alertsData);
      setHealthStatus(healthData);
    } catch (error) {
      console.error('获取实时数据失败:', error);
      message.error('获取实时数据失败');
    } finally {
      setLoading(false);
    }
  }, [monitoringService, selectedTimeRange]);

  // 获取性能统计
  const fetchPerformanceStats = useCallback(async () => {
    try {
      const stats = await monitoringService.getPerformanceStats(selectedTimeRange);
      setPerformanceStats(stats);
    } catch (error) {
      console.error('获取性能统计失败:', error);
    }
  }, [monitoringService, selectedTimeRange]);

  // 初始化数据
  useEffect(() => {
    fetchRealTimeData();
    fetchPerformanceStats();
    
    // 设置定时刷新
    const interval = setInterval(() => {
      if (activeTab === 'realtime') {
        fetchRealTimeData();
      }
    }, dashboardConfig.refreshInterval);
    
    return () => clearInterval(interval);
  }, [fetchRealTimeData, fetchPerformanceStats, dashboardConfig.refreshInterval, activeTab]);

  // 处理配置更新
  const handleConfigUpdate = (values: Partial<DashboardConfig>) => {
    setDashboardConfig(prev => ({ ...prev, ...values }));
    setSettingsModalVisible(false);
    message.success('配置已更新');
  };

  // 处理告警确认
  const handleAlertAcknowledge = async (alertId: string) => {
    try {
      await monitoringService.acknowledgeAlert(alertId);
      setAlerts(prev => prev.map(alert => 
        alert.id === alertId ? { ...alert, status: 'resolved' as const } : alert
      ));
      message.success('告警已确认');
    } catch (error) {
      message.error('确认告警失败');
    }
  };

  // 处理全屏切换
  const handleFullscreenToggle = () => {
    if (!isFullscreen) {
      const elem = document.documentElement;
      if (elem.requestFullscreen) {
        elem.requestFullscreen();
      }
    } else {
      if (document.exitFullscreen) {
        document.exitFullscreen();
      }
    }
    setIsFullscreen(!isFullscreen);
  };

  // 导出数据
  const handleExportData = async (format: 'json' | 'csv') => {
    try {
      const blob = await monitoringService.exportData(selectedTimeRange, format);
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `monitoring-data-${new Date().toISOString().split('T')[0]}.${format}`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
      message.success('数据导出成功');
    } catch (error) {
      message.error('导出数据失败');
    }
  };

  // 获取告警统计
  const getAlertStats = () => {
    const activeAlerts = alerts.filter(a => a.status === 'active');
    const critical = activeAlerts.filter(a => a.severity === 'critical').length;
    const high = activeAlerts.filter(a => a.severity === 'high').length;
    const medium = activeAlerts.filter(a => a.severity === 'medium').length;
    const low = activeAlerts.filter(a => a.severity === 'low').length;
    
    return { total: activeAlerts.length, critical, high, medium, low };
  };

  // 监听全屏变化
  useEffect(() => {
    const handleFullscreenChange = () => {
      setIsFullscreen(!!document.fullscreenElement);
    };
    
    document.addEventListener('fullscreenchange', handleFullscreenChange);
    return () => document.removeEventListener('fullscreenchange', handleFullscreenChange);
  }, []);

  const alertStats = getAlertStats();
  const latestMetrics = realTimeMetrics[realTimeMetrics.length - 1];

  return (
    <div className={`monitoring-dashboard ${dashboardConfig.theme}`}>
      {/* 页面头部 */}
      <div className="dashboard-header">
        <Row justify="space-between" align="middle">
          <Col>
            <Title level={2}>
              <DashboardOutlined /> 系统监控中心
            </Title>
            <Text type="secondary">
              实时监控系统性能、告警和健康状态
            </Text>
          </Col>
          
          <Col>
            <Space>
              <Select 
                value={selectedTimeRange} 
                onChange={setSelectedTimeRange}
                style={{ width: 120 }}
              >
                <Option value="5m">5分钟</Option>
                <Option value="15m">15分钟</Option>
                <Option value="1h">1小时</Option>
                <Option value="6h">6小时</Option>
                <Option value="24h">24小时</Option>
                <Option value="7d">7天</Option>
                <Option value="30d">30天</Option>
              </Select>
              
              <Button 
                icon={<ReloadOutlined />} 
                onClick={fetchRealTimeData}
                loading={loading}
              >
                刷新
              </Button>
              
              <Button 
                icon={<SettingOutlined />} 
                onClick={() => setSettingsModalVisible(true)}
              >
                设置
              </Button>
              
              <Button 
                icon={isFullscreen ? <ShrinkOutlined /> : <FullscreenOutlined />}
                onClick={handleFullscreenToggle}
              >
                {isFullscreen ? '退出全屏' : '全屏'}
              </Button>
            </Space>
          </Col>
        </Row>
      </div>

      {/* 系统状态概览 */}
      <Row gutter={[16, 16]} className="status-overview">
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="系统状态"
              value={healthStatus?.status === 'healthy' ? 100 : 
                      healthStatus?.status === 'warning' ? 75 : 25}
              suffix="%"
              valueStyle={{ 
                color: healthStatus?.status === 'healthy' ? '#3f8600' : 
                       healthStatus?.status === 'warning' ? '#fa8c16' : '#cf1322'
              }}
              prefix={<DashboardOutlined />}
            />
            <div style={{ marginTop: 8 }}>
              <Tag color={healthStatus?.status === 'healthy' ? 'green' : 
                           healthStatus?.status === 'warning' ? 'orange' : 'red'}>
                {healthStatus?.status === 'healthy' ? '健康' : 
                 healthStatus?.status === 'warning' ? '警告' : '严重'}
              </Tag>
            </div>
          </Card>
        </Col>
        
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="活跃告警"
              value={alertStats.total}
              valueStyle={{ color: alertStats.critical > 0 ? '#cf1322' : '#1890ff' }}
              prefix={<BellOutlined />}
            />
            <div style={{ marginTop: 8 }}>
              <Space>
                <Tag color="red">严重: {alertStats.critical}</Tag>
                <Tag color="orange">高级: {alertStats.high}</Tag>
              </Space>
            </div>
          </Card>
        </Col>
        
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="平均响应时间"
              value={latestMetrics?.responseTime || 0}
              suffix="ms"
              valueStyle={{ color: '#1890ff' }}
              prefix={<LineChartOutlined />}
            />
            <div style={{ marginTop: 8 }}>
              <Text type="secondary">
                延迟: {(latestMetrics?.responseTime || 0) > dashboardConfig.alertThresholds.responseTime ? '高' : '正常'}
              </Text>
            </div>
          </Card>
        </Col>
        
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="系统可用性"
              value={performanceStats?.availability || 99.9}
              suffix="%"
              valueStyle={{ color: '#3f8600' }}
              prefix={<CheckCircleOutlined />}
            />
            <div style={{ marginTop: 8 }}>
              <Text type="secondary">
                过去24小时
              </Text>
            </div>
          </Card>
        </Col>
      </Row>

      {/* 主要内容区域 */}
      <Spin spinning={loading}>
        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          type="card"
          className="dashboard-tabs"
          items={[
            {
              key: 'realtime',
              label: (
                <span>
                  <LineChartOutlined />
                  实时监控
                </span>
              ),
              children: <RealTimeDashboard />
            },
            {
              key: 'performance',
              label: (
                <span>
                  <BarChartOutlined />
                  性能分析
                </span>
              ),
              children: (
                <PerformanceAnalysis
                  metrics={realTimeMetrics}
                  stats={performanceStats}
                  timeRange={selectedTimeRange}
                />
              )
            },
            {
              key: 'alerts',
              label: (
                <span>
                  <PieChartOutlined />
                  告警管理
                </span>
              ),
              children: (
                <AlertManagement
                  alerts={alerts}
                  onAcknowledge={handleAlertAcknowledge}
                  onSettings={() => setAlertRulesModalVisible(true)}
                />
              )
            },
            {
              key: 'settings',
              label: (
                <span>
                  <SettingOutlined />
                  系统设置
                </span>
              ),
              children: (
                <SystemSettings
                  config={dashboardConfig}
                  onConfigUpdate={handleConfigUpdate}
                  healthStatus={healthStatus}
                />
              )
            }
          ]}
        />
      </Spin>

      {/* 设置模态框 */}
      <Modal
        title="仪表板设置"
        open={settingsModalVisible}
        onCancel={() => setSettingsModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          layout="vertical"
          initialValues={dashboardConfig}
          onFinish={handleConfigUpdate}
        >
          <Form.Item label="刷新间隔(毫秒)" name="refreshInterval">
            <InputNumber min={1000} max={60000} step={1000} />
          </Form.Item>
          
          <Form.Item label="主题" name="theme">
            <Select>
              <Option value="light">浅色主题</Option>
              <Option value="dark">深色主题</Option>
            </Select>
          </Form.Item>
          
          <Divider>告警阈值</Divider>
          
          <Form.Item label="CPU使用率阈值(%)" name={['alertThresholds', 'cpu']}>
            <InputNumber min={0} max={100} step={5} />
          </Form.Item>
          
          <Form.Item label="内存使用率阈值(%)" name={['alertThresholds', 'memory']}>
            <InputNumber min={0} max={100} step={5} />
          </Form.Item>
          
          <Form.Item label="磁盘使用率阈值(%)" name={['alertThresholds', 'disk']}>
            <InputNumber min={0} max={100} step={5} />
          </Form.Item>
          
          <Form.Item label="响应时间阈值(ms)" name={['alertThresholds', 'responseTime']}>
            <InputNumber min={100} max={30000} step={100} />
          </Form.Item>
          
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                保存
              </Button>
              <Button onClick={() => setSettingsModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

// 性能分析组件
const PerformanceAnalysis: React.FC<{
  metrics: SystemMetrics[];
  stats: PerformanceStats | null;
  timeRange: TimeRange;
}> = ({ metrics, stats, timeRange }) => {
  return (
    <div className="performance-analysis">
      <Row gutter={[16, 16]}>
        <Col xs={24} lg={12}>
          <Card title="性能统计">
            {stats && (
              <Row gutter={[16, 16]}>
                <Col span={12}>
                  <Statistic title="平均CPU使用率" value={stats.avgCpuUsage.toFixed(1)} suffix="%" />
                </Col>
                <Col span={12}>
                  <Statistic title="最大CPU使用率" value={stats.maxCpuUsage.toFixed(1)} suffix="%" />
                </Col>
                <Col span={12}>
                  <Statistic title="平均内存使用率" value={stats.avgMemoryUsage.toFixed(1)} suffix="%" />
                </Col>
                <Col span={12}>
                  <Statistic title="最大内存使用率" value={stats.maxMemoryUsage.toFixed(1)} suffix="%" />
                </Col>
                <Col span={12}>
                  <Statistic title="平均响应时间" value={stats.avgResponseTime.toFixed(0)} suffix="ms" />
                </Col>
                <Col span={12}>
                  <Statistic title="错误率" value={stats.errorRate.toFixed(2)} suffix="%" />
                </Col>
              </Row>
            )}
          </Card>
        </Col>
        
        <Col xs={24} lg={12}>
          <Card title="系统负载">
            <Space direction="vertical" style={{ width: '100%' }}>
              <div>
                <Text>CPU负载</Text>
                <Progress 
                  percent={metrics.length > 0 ? metrics[metrics.length - 1].cpuUsage : 0} 
                  showInfo={false}
                />
              </div>
              <div>
                <Text>内存负载</Text>
                <Progress 
                  percent={metrics.length > 0 ? metrics[metrics.length - 1].memoryUsage : 0} 
                  showInfo={false}
                />
              </div>
              <div>
                <Text>磁盘负载</Text>
                <Progress 
                  percent={metrics.length > 0 ? metrics[metrics.length - 1].diskUsage : 0} 
                  showInfo={false}
                />
              </div>
            </Space>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

// 告警管理组件
const AlertManagement: React.FC<{
  alerts: AlertInfo[];
  onAcknowledge: (id: string) => void;
  onSettings: () => void;
}> = ({ alerts, onAcknowledge, onSettings }) => {
  const activeAlerts = alerts.filter(a => a.status === 'active');
  
  return (
    <div className="alert-management">
      <Card 
        title="告警列表" 
        extra={
          <Button icon={<SettingOutlined />} onClick={onSettings}>
            告警设置
          </Button>
        }
      >
        <Space direction="vertical" style={{ width: '100%' }}>
          {activeAlerts.map(alert => (
            <Alert
              key={alert.id}
              message={alert.title}
              description={alert.message}
              type={alert.type}
              showIcon
              action={
                <Button size="small" type="primary" onClick={() => onAcknowledge(alert.id)}>
                  确认
                </Button>
              }
              style={{ marginBottom: 8 }}
            />
          ))}
          
          {activeAlerts.length === 0 && (
            <Alert
              message="暂无活跃告警"
              description="系统运行正常，没有需要处理的告警"
              type="success"
              showIcon
            />
          )}
        </Space>
      </Card>
    </div>
  );
};

// 系统设置组件
const SystemSettings: React.FC<{
  config: DashboardConfig;
  onConfigUpdate: (config: Partial<DashboardConfig>) => void;
  healthStatus: HealthStatus | null;
}> = ({ config, onConfigUpdate, healthStatus }) => {
  return (
    <div className="system-settings">
      <Row gutter={[16, 16]}>
        <Col xs={24} lg={12}>
          <Card title="系统信息">
            <Space direction="vertical" style={{ width: '100%' }}>
              <div>
                <Text strong>系统状态：</Text>
                <Tag color={healthStatus?.status === 'healthy' ? 'green' : 
                             healthStatus?.status === 'warning' ? 'orange' : 'red'}>
                  {healthStatus?.status === 'healthy' ? '健康' : 
                   healthStatus?.status === 'warning' ? '警告' : '严重'}
                </Tag>
              </div>
              
              {healthStatus && (
                <>
                  <Divider />
                  <div>
                    <Text strong>数据库状态：</Text>
                    <Tag color={healthStatus.components.database === 'healthy' ? 'green' : 'red'}>
                      {healthStatus.components.database === 'healthy' ? '正常' : '异常'}
                    </Tag>
                  </div>
                  <div>
                    <Text strong>缓存状态：</Text>
                    <Tag color={healthStatus.components.cache === 'healthy' ? 'green' : 'red'}>
                      {healthStatus.components.cache === 'healthy' ? '正常' : '异常'}
                    </Tag>
                  </div>
                  <div>
                    <Text strong>外部服务状态：</Text>
                    <Tag color={healthStatus.components.externalServices === 'healthy' ? 'green' : 'red'}>
                      {healthStatus.components.externalServices === 'healthy' ? '正常' : '异常'}
                    </Tag>
                  </div>
                  <div>
                    <Text strong>消息队列状态：</Text>
                    <Tag color={healthStatus.components.messageQueue === 'healthy' ? 'green' : 'red'}>
                      {healthStatus.components.messageQueue === 'healthy' ? '正常' : '异常'}
                    </Tag>
                  </div>
                </>
              )}
            </Space>
          </Card>
        </Col>
        
        <Col xs={24} lg={12}>
          <Card title="告警阈值配置">
            <Space direction="vertical" style={{ width: '100%' }}>
              <div>
                <Text>CPU使用率阈值：{config.alertThresholds.cpu}%</Text>
                <Progress percent={config.alertThresholds.cpu} showInfo={false} />
              </div>
              <div>
                <Text>内存使用率阈值：{config.alertThresholds.memory}%</Text>
                <Progress percent={config.alertThresholds.memory} showInfo={false} />
              </div>
              <div>
                <Text>磁盘使用率阈值：{config.alertThresholds.disk}%</Text>
                <Progress percent={config.alertThresholds.disk} showInfo={false} />
              </div>
              <div>
                <Text>响应时间阈值：{config.alertThresholds.responseTime}ms</Text>
              </div>
            </Space>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default MonitoringDashboard;